<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>

</head>

<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        //获取按钮
        let btns = document.querySelectorAll('button');
        //1. 声明外层变量
        let cancel = null;

        //绑定事件 xhr.abort();
        btns[0].onclick = async function(){
            //发送请求之前, 检测是否有请求正在发送
            if(cancel) cancel();

            let result = await axios({
                url: 'http://127.0.0.1:8023/server',
                //2. 设置取消的操作
                cancelToken: new axios.CancelToken(c => {
                    cancel = c;
                })
            })
        }

        btns[1].onclick = function(){
            //3. 合适的时机调用 cancel 函数
            if(typeof cancel === 'function'){
                cancel();
            }
        }
    </script>
</body>

</html>